package com.atguigu.flink.chapter06;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/1/22 13:52
 */
public class Flink02_PV {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);

        // 1.读取数据、转换成 POJO
        SingleOutputStreamOperator<UserBehavior> userBehaviorDS = env
                .readTextFile("input/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return new UserBehavior(
                                Long.valueOf(datas[0]),
                                Long.valueOf(datas[1]),
                                Integer.valueOf(datas[2]),
                                datas[3],
                                Long.valueOf(datas[4])
                        );
                    }
                });

        // 2.处理数据
        userBehaviorDS
                .filter(r -> "pv".equals(r.getBehavior()))  // 2.1 过滤出 pv 行为
/*                .keyBy(r -> r.getBehavior())
                .process(new KeyedProcessFunction<String, UserBehavior, Long>() {
                    private Long pvCount = 0L;

                    @Override
                    public void processElement(UserBehavior value, Context ctx, Collector<Long> out) throws Exception {
                        pvCount++;
                        out.collect(pvCount);
                    }
                })*/
                .process(new ProcessFunction<UserBehavior, Long>() {
                    private Long pvCount = 0L;
                    @Override
                    public void processElement(UserBehavior value, Context ctx, Collector<Long> out) throws Exception {
                        pvCount++;
                        out.collect(pvCount);
                    }
                }).setParallelism(1)
                .print();

        env.execute();
    }
}
